package com.mychessproject;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.DialogInterface;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnTouchListener{

	static final String TAG = "WeAndroids";
	
	private ImageView[] chess_piece_squares;
	private int[][] chess_piece_locationxy;
	private int[] chess_piece_pictures;
	
	private Button start_btn;
	private Button movernd_btn;

	private int chess_square_selected_from=-1;
	private int chess_square_selected=-1;
	private int chess_square_selected_to=-1;
	
	//final static String[] chess_pieces_names={"","BRook","BKnight","BBishop","BQueen","BKing","BPawn","WRook","WKnight","WBishop","WQueen","WKing","WPawn"};
    private int[] chess_pieces_images ={R.drawable.blank_piece, R.drawable.black_rook,R.drawable.black_knight,R.drawable.black_bishop,R.drawable.black_queen,R.drawable.black_king,R.drawable.black_pawn,R.drawable.white_rook,R.drawable.white_knight,R.drawable.white_bishop,R.drawable.white_queen,R.drawable.white_king,R.drawable.white_pawn};
	
	private MediaPlayer mMediaPlayer;
	
	private TextView chess_turn_tv;
	private int chess_turn_status=0;
	private int king_in_check_status=0;
	private int winning_status=0;
	private Chess mychess;
	
	private boolean random_move_click=false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		mychess=new Chess();
		mychess.init();
		mMediaPlayer=new MediaPlayer();
		
		chess_piece_squares=new ImageView[64];
		chess_piece_pictures=new int[64];
		chess_piece_locationxy=new int[64][2];
		
		start_btn= (Button) findViewById(R.id.start_btn);
		movernd_btn= (Button) findViewById(R.id.movernd_btn);
		
		chess_turn_tv = (TextView) findViewById(R.id.chess_turn_tv);
		
		chess_piece_squares[0] = (ImageView) findViewById(R.id.chess_sq_11);
		chess_piece_squares[1] = (ImageView) findViewById(R.id.chess_sq_12);
		chess_piece_squares[2] = (ImageView) findViewById(R.id.chess_sq_13);
		chess_piece_squares[3] = (ImageView) findViewById(R.id.chess_sq_14);
		chess_piece_squares[4] = (ImageView) findViewById(R.id.chess_sq_15);
		chess_piece_squares[5] = (ImageView) findViewById(R.id.chess_sq_16);
		chess_piece_squares[6] = (ImageView) findViewById(R.id.chess_sq_17);
		chess_piece_squares[7] = (ImageView) findViewById(R.id.chess_sq_18);

		chess_piece_squares[8] = (ImageView) findViewById(R.id.chess_sq_21);
		chess_piece_squares[9] = (ImageView) findViewById(R.id.chess_sq_22);
		chess_piece_squares[10] = (ImageView) findViewById(R.id.chess_sq_23);
		chess_piece_squares[11] = (ImageView) findViewById(R.id.chess_sq_24);
		chess_piece_squares[12] = (ImageView) findViewById(R.id.chess_sq_25);
		chess_piece_squares[13] = (ImageView) findViewById(R.id.chess_sq_26);
		chess_piece_squares[14] = (ImageView) findViewById(R.id.chess_sq_27);
		chess_piece_squares[15] = (ImageView) findViewById(R.id.chess_sq_28);

		chess_piece_squares[16] = (ImageView) findViewById(R.id.chess_sq_31);
		chess_piece_squares[17] = (ImageView) findViewById(R.id.chess_sq_32);
		chess_piece_squares[18] = (ImageView) findViewById(R.id.chess_sq_33);
		chess_piece_squares[19] = (ImageView) findViewById(R.id.chess_sq_34);
		chess_piece_squares[20] = (ImageView) findViewById(R.id.chess_sq_35);
		chess_piece_squares[21] = (ImageView) findViewById(R.id.chess_sq_36);
		chess_piece_squares[22] = (ImageView) findViewById(R.id.chess_sq_37);
		chess_piece_squares[23] = (ImageView) findViewById(R.id.chess_sq_38);

		chess_piece_squares[24] = (ImageView) findViewById(R.id.chess_sq_41);
		chess_piece_squares[25] = (ImageView) findViewById(R.id.chess_sq_42);
		chess_piece_squares[26] = (ImageView) findViewById(R.id.chess_sq_43);
		chess_piece_squares[27] = (ImageView) findViewById(R.id.chess_sq_44);
		chess_piece_squares[28] = (ImageView) findViewById(R.id.chess_sq_45);
		chess_piece_squares[29] = (ImageView) findViewById(R.id.chess_sq_46);
		chess_piece_squares[30] = (ImageView) findViewById(R.id.chess_sq_47);
		chess_piece_squares[31] = (ImageView) findViewById(R.id.chess_sq_48);

		chess_piece_squares[32] = (ImageView) findViewById(R.id.chess_sq_51);
		chess_piece_squares[33] = (ImageView) findViewById(R.id.chess_sq_52);
		chess_piece_squares[34] = (ImageView) findViewById(R.id.chess_sq_53);
		chess_piece_squares[35] = (ImageView) findViewById(R.id.chess_sq_54);
		chess_piece_squares[36] = (ImageView) findViewById(R.id.chess_sq_55);
		chess_piece_squares[37] = (ImageView) findViewById(R.id.chess_sq_56);
		chess_piece_squares[38] = (ImageView) findViewById(R.id.chess_sq_57);
		chess_piece_squares[39] = (ImageView) findViewById(R.id.chess_sq_58);

		chess_piece_squares[40] = (ImageView) findViewById(R.id.chess_sq_61);
		chess_piece_squares[41] = (ImageView) findViewById(R.id.chess_sq_62);
		chess_piece_squares[42] = (ImageView) findViewById(R.id.chess_sq_63);
		chess_piece_squares[43] = (ImageView) findViewById(R.id.chess_sq_64);
		chess_piece_squares[44] = (ImageView) findViewById(R.id.chess_sq_65);
		chess_piece_squares[45] = (ImageView) findViewById(R.id.chess_sq_66);
		chess_piece_squares[46] = (ImageView) findViewById(R.id.chess_sq_67);
		chess_piece_squares[47] = (ImageView) findViewById(R.id.chess_sq_68);

		chess_piece_squares[48] = (ImageView) findViewById(R.id.chess_sq_71);
		chess_piece_squares[49] = (ImageView) findViewById(R.id.chess_sq_72);
		chess_piece_squares[50] = (ImageView) findViewById(R.id.chess_sq_73);
		chess_piece_squares[51] = (ImageView) findViewById(R.id.chess_sq_74);
		chess_piece_squares[52] = (ImageView) findViewById(R.id.chess_sq_75);
		chess_piece_squares[53] = (ImageView) findViewById(R.id.chess_sq_76);
		chess_piece_squares[54] = (ImageView) findViewById(R.id.chess_sq_77);
		chess_piece_squares[55] = (ImageView) findViewById(R.id.chess_sq_78);

		chess_piece_squares[56] = (ImageView) findViewById(R.id.chess_sq_81);
		chess_piece_squares[57] = (ImageView) findViewById(R.id.chess_sq_82);
		chess_piece_squares[58] = (ImageView) findViewById(R.id.chess_sq_83);
		chess_piece_squares[59] = (ImageView) findViewById(R.id.chess_sq_84);
		chess_piece_squares[60] = (ImageView) findViewById(R.id.chess_sq_85);
		chess_piece_squares[61] = (ImageView) findViewById(R.id.chess_sq_86);
		chess_piece_squares[62] = (ImageView) findViewById(R.id.chess_sq_87);
		chess_piece_squares[63] = (ImageView) findViewById(R.id.chess_sq_88);
		
		for (int i = 0; i < chess_piece_squares.length; i++) {
			chess_piece_squares[i].setOnTouchListener(this);
		}
		
		View.OnClickListener VClick=new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switch(v.getId()){
				
				case R.id.start_btn:
					for (int i = 0; i < chess_piece_squares.length; i++) {
						chess_piece_squares[i].getLocationOnScreen(chess_piece_locationxy[i]);
					}
					Chess_Init();
					break;
				
				case R.id.movernd_btn:
					random_move();
					break;
				}
			}
		};
		
		start_btn.setOnClickListener(VClick);
		movernd_btn.setOnClickListener(VClick);
		
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		
		if(event.getAction()==MotionEvent.ACTION_DOWN)
		{
			Log.d(TAG, "Touch Down");
			
			for (int i = 0; i < chess_piece_squares.length; i++)
			{
				//if the chess piece square is touched and it is not blank
				if(v.equals(chess_piece_squares[i])&chess_piece_pictures[i]!=chess_pieces_images[0])
				{
					chess_square_selected_from=i;
					chess_square_selected_to=i;
				}
			}
		}
		
		if(event.getAction()==MotionEvent.ACTION_UP)
		{
			Log.d(TAG, "Touch Up");
			move_chess_pieces(chess_square_selected_from,chess_square_selected_to);
		}
		
		if(event.getAction()==MotionEvent.ACTION_MOVE)
		{
			Log.d(TAG, "Touch Move"+event.getRawX()+" "+event.getRawY());
			if(chess_square_selected_from>=0)
			{
				 int moveX=(int) event.getRawX();
				 int moveY=(int) event.getRawY();

				 for (int i = 0; i < chess_piece_squares.length; i++) {
					 if(moveX>=chess_piece_locationxy[i][0] && moveX<=chess_piece_locationxy[i][0]+chess_piece_squares[i].getWidth())
							if(moveY>=chess_piece_locationxy[i][1] && moveY<=chess_piece_locationxy[i][1]+chess_piece_squares[i].getHeight()) {
								//chess_square_selected is the Current square 
								Log.d(TAG, "Move To "+i);
								chess_square_selected=i;
								chess_piece_squares[chess_square_selected].setImageResource(chess_piece_pictures[chess_square_selected_from]);
								
								//if it is moving, the previous chess piece square must restore the original one
								if(chess_square_selected_to!=chess_square_selected)
								{
									chess_piece_squares[chess_square_selected_to].setImageResource(chess_piece_pictures[chess_square_selected_to]);
									chess_square_selected_to=chess_square_selected;
									playSounds(R.raw.soundmove);
								}
						}
				 }
			}
			
		}
		return true;
	}
	
	private void Chess_Init()
	{
		mychess.init();
		update_chess_board();

		chess_square_selected_from=-1;
		chess_square_selected_to=-1;

		chess_turn_status=mychess.getchess_turn_status();
		if(chess_turn_status==0)
			chess_turn_tv.setText("White Turn");
		else
			chess_turn_tv.setText("Black Turn");

		playSounds(R.raw.sound26);
	}
	
	//Move the chess piece from move_from to move_to
	private void move_chess_pieces(int move_from, int move_to)
	{
		if(move_from!=move_to)
		{
			boolean movable=mychess.chess_rules_check(move_from,move_to,0);
			if(movable)
			{
				int taking=mychess.move_chess_pieces(move_from, move_to);
				if(taking==1)
				{
					playSounds(R.raw.sound09);
				}
			
				//check the pawn chess piece if it goes to the last row
				check_pawns_promote(move_to);
			
				//Update the chess board
				update_chess_board();
			
				//check the King if it is in check status
				king_in_check_status=mychess.king_in_check_status();
			
				if(king_in_check_status==1)
					Toast.makeText(MainActivity.this, "White King in check status", Toast.LENGTH_SHORT).show();
			
				if(king_in_check_status==2)
					Toast.makeText(MainActivity.this, "Black King in check status", Toast.LENGTH_SHORT).show();
			
				//Check if there is a winning Status
				winning_status=mychess.winning_status();
				if(winning_status==1)  
				{
					new AlertDialog.Builder(MainActivity.this)
					.setTitle("Notice")
					.setMessage("White chess wins")
					.setPositiveButton("OK", new DialogInterface.OnClickListener() 
					{

						@Override
						public void onClick(DialogInterface dialog, int arg1) {
						// TODO Auto-generated method stub
							Chess_Init();
							dialog.dismiss();
						}
					}).show();
				}
			
				if(winning_status==2)
				{
					new AlertDialog.Builder(MainActivity.this)
					.setTitle("Notice")
					.setMessage("Black chess wins")
					.setPositiveButton("OK", new DialogInterface.OnClickListener() 
					{	

						@Override
						public void onClick(DialogInterface dialog, int arg1) {
						// TODO Auto-generated method stub
							Chess_Init();
							dialog.dismiss();
						}
					
					}).show();
				}
							
				//update the chess piece turn text
				chess_turn_status=mychess.getchess_turn_status();
				if(chess_turn_status==0)
					chess_turn_tv.setText("White Turn");
				else
					chess_turn_tv.setText("Black Turn");
		}
		 else
		 {
			//check if it is turn error
			int chess_turn_error = mychess.getchess_turn_error();
			if(chess_turn_error==1)
				Toast.makeText(MainActivity.this, "Now is White Turn", Toast.LENGTH_SHORT).show();
				
			if(chess_turn_error==2)
				Toast.makeText(MainActivity.this, "Now is Black Turn", Toast.LENGTH_SHORT).show();
				
			playSounds(R.raw.sound11);
			
			//if it is not turn error
			if(chess_turn_error==0)
				Toast.makeText(MainActivity.this, "Invalid Moving", Toast.LENGTH_SHORT).show();
			
			//update the chess board
			update_chess_board();
		 }
		}
	}
	
	//update the chess board
	//update all the chess pieces by the chess_pieces_positions of the Chess Class
	private void update_chess_board()
	{
		for(int i=0;i<chess_piece_squares.length;i++)
		{
			chess_piece_squares[i].setImageResource(chess_pieces_images[mychess.getchess_pieces_positions(i)]);
			chess_piece_pictures[i]=chess_pieces_images[mychess.getchess_pieces_positions(i)];
		}
	}
	
	//Pawns move to the bottom line and promote to  Queen or Rook or Knight or Bishop
	private void check_pawns_promote(int move_to)
	{
		// Get Pawn last line status
		int pawn_last_row_status = mychess.getpawn_last_row_status();
	
		Log.d(TAG, "pawn_last_row_status"+pawn_last_row_status);
		
		//Black Pawn goes to the last line (7 line)
		if(pawn_last_row_status==2)
		{
			final int chess_position = move_to;
			new AlertDialog.Builder(this).setTitle("Replace the Pawn by").setSingleChoiceItems(
				     new String[] { "Queen", "Rook","Knight","Bishop"}, 0,
				     new DialogInterface.OnClickListener() {
				      public void onClick(DialogInterface dialog, int which) {
				    	  switch(which)
				    	  {
				    	  	case 0:
				    	  		mychess.setchess_pieces_positions(chess_position%8, chess_position/8, 4);
				    	  		break;
				    	  	case 1:
				    	  		mychess.setchess_pieces_positions(chess_position%8, chess_position/8, 1);
					    		break;
				    	  	case 2:
				    	  		mychess.setchess_pieces_positions(chess_position%8, chess_position/8, 2);
					    		break;		
				    	  	case 3:
				    	  		mychess.setchess_pieces_positions(chess_position%8, chess_position/8, 3);
					    		break;									    		
				    	  }
				    	  playSounds(R.raw.sound09);
				    	  update_chess_board();
				    	  
				    	  king_in_check_status=mychess.king_in_check_status();
				    	  
				    	  if(king_in_check_status==1)
								Toast.makeText(MainActivity.this, "White King in check status", Toast.LENGTH_SHORT).show();
							
						  if(king_in_check_status==2)
								Toast.makeText(MainActivity.this, "Black King in check status", Toast.LENGTH_SHORT).show();
						  
				    	  dialog.dismiss();
				      }
				     }).show();
		}
	
	//White Pawn goes to the last line  (0 line)
	if(pawn_last_row_status==1)
	{
		final int chess_position = move_to;
		new AlertDialog.Builder(this).setTitle("Replace the Pawn by").setSingleChoiceItems(
				     new String[] { "Queen", "Rook","Knight","Bishop"}, 0,
				     new DialogInterface.OnClickListener() {
				      public void onClick(DialogInterface dialog, int which) {
				    	  switch(which)
				    	  {
				    	  	case 0:
				    	  		mychess.setchess_pieces_positions(chess_position%8, chess_position/8, 10);
				    	  		break;
				    		
				    	  	case 1:
				    	  		mychess.setchess_pieces_positions(chess_position%8, chess_position/8, 7);
					    		break;
					    		
				    	  	case 2:
				    	  		mychess.setchess_pieces_positions(chess_position%8, chess_position/8, 8);
					    		break;		
					    		
				    	  	case 3:
				    	  		mychess.setchess_pieces_positions(chess_position%8, chess_position/8, 9);
					    		break;									    		
				    	  }
				    	  playSounds(R.raw.sound09);
				    	  update_chess_board();
				    	  
				    	  king_in_check_status=mychess.king_in_check_status();
				    	  
				    	  if(king_in_check_status==1)
								Toast.makeText(MainActivity.this, "White King in check status", Toast.LENGTH_SHORT).show();
							
						  if(king_in_check_status==2)
								Toast.makeText(MainActivity.this, "Black King in check status", Toast.LENGTH_SHORT).show();
				    	  
				    	  dialog.dismiss();
				      }
				     }).show();
	}
	
	mychess.setpawn_last_row_status(0);
	
	}
	
	private void playSounds(int sid) {

		if (mMediaPlayer != null) {
			if (mMediaPlayer.isPlaying()) {
				mMediaPlayer.stop();
			}
			mMediaPlayer.release();
			mMediaPlayer = null;
		}

		mMediaPlayer = MediaPlayer.create(MainActivity.this, sid);
		mMediaPlayer.start();
	}
	
	private void random_move()
	{
		if(random_move_click)
			return;
		
		random_move_click=true;
		boolean random_movable=mychess.random_move();
		if(random_movable)
		{
		  int random_move_from = mychess.getrandom_move_from();
		  int random_move_to = mychess.getrandom_move_to();
		  
		  Log.d(TAG, "random_move_from"+random_move_from);
		  Log.d(TAG, "random_move_to"+random_move_to);
		  move_chess_pieces(random_move_from,random_move_to);
		}
		random_move_click=false;
	}
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	AudioManager audioManager=null;
    	audioManager=(AudioManager)getSystemService(Service.AUDIO_SERVICE);

    if(keyCode==KeyEvent.KEYCODE_VOLUME_DOWN){
    	audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, 
                AudioManager.ADJUST_LOWER, 
                AudioManager.FLAG_SHOW_UI);
        	return true;
    }else if(keyCode==KeyEvent.KEYCODE_VOLUME_UP)
    {
    	audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, 
                AudioManager.ADJUST_RAISE, 
                AudioManager.FLAG_SHOW_UI);    
    		return true;
    }else if(keyCode==KeyEvent.KEYCODE_BACK)
    {
    	return super.onKeyDown(keyCode, event);    
    }else{
    return super.onKeyDown(keyCode, event);    
    }
    }
	
}
